import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/event/LoginEvent.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/login/ResetPwd.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/LoadingUtil.dart';
import 'package:panda/util/SignUtil.dart';
import 'Register.dart';

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return LoginView();
  }
}

class LoginView extends State<LoginPage> {
  TextEditingController schoolController = new TextEditingController();
  TextEditingController userController = new TextEditingController();
  TextEditingController passController = new TextEditingController();
  TextEditingController codeController = new TextEditingController();

  bool codeOpen = false;
  Timer _countdownTimer;
  int _countdownNum = 59;
  String codeString = "获取验证码";
  int codeStatus = 1;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(PHONE).then((value) {
      if (value != null) {
        userController.text = value;
        setState(() {});
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return new Scaffold(
        appBar: new AppBar(
          title: new Text(
            "登录",
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black),
          ),
          elevation: 0.5,
          backgroundColor: Colors.white,
          brightness: Brightness.light,
          centerTitle: true,
          iconTheme: new IconThemeData(color: Colors.black),
          actions: <Widget>[
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              child: Container(
                alignment: Alignment.center,
                padding: EdgeInsets.fromLTRB(0, 0, 13, 0),
                child: Text(
                  !codeOpen ? '短信登录' : '密码登录',
                  style: TextStyle(
                      fontSize:
                          ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE + 1),
                      color: Colors.black54),
                ),
              ),
              onTap: () {
                codeOpen = !codeOpen;
                setState(() {});
              },
            )
          ],
        ),
        body: Container(
          color: white,
          child: new ListView(
            children: <Widget>[
              new Column(
                children: <Widget>[
                  loginTopImg(),
                  loginUserEditInput(),
                  new Container(
                    padding: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setWidth(DP_100),
                        0.0,
                        ScreenUtil.getInstance().setWidth(DP_100),
                        0.0),
                    child: Divider(
                      height: 1,
                      color: Colors.grey,
                    ),
                  ),
                  Offstage(
                    offstage: !codeOpen,
                    child: loginUserCodeInput(),
                  ),
                  Offstage(
                    offstage: codeOpen,
                    child: loginPassEditInput(),
                  ),
                  new Container(
                    padding: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setWidth(DP_100),
                        0.0,
                        ScreenUtil.getInstance().setWidth(DP_100),
                        0.0),
                    child: Divider(
                      height: 1,
                      color: Colors.grey,
                    ),
                  ),
                  loginButton(context),
                  Offstage(
                    offstage: codeOpen,
                    child: loginTip(context),
                  ),
                  // initMoreLogin(context),
                  // Padding(
                  //     padding: EdgeInsets.all(
                  //         ScreenUtil.getInstance().setHeight(10)),
                  //     child: new GestureDetector(
                  //         onTap: () {},
                  //         child: Column(
                  //           children: <Widget>[
                  //             Image.asset(
                  //               'images/login_wx.png',
                  //             ),
                  //             Padding(
                  //               padding: EdgeInsets.all(10),
                  //               child: Text(
                  //                 '微信登录',
                  //                 style: TextStyle(fontSize: 14),
                  //               ),
                  //             )
                  //           ],
                  //         )))
                ],
              )
            ],
          ),
        ));
  }

  Widget loginUserCodeInput() {
    return new Padding(
      padding: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(DP_100),
          10.0, ScreenUtil.getInstance().setWidth(DP_100), 0.0),
      child: new Stack(
        alignment: Alignment(1.0, 1.0),
        children: <Widget>[
          new Row(
            children: <Widget>[
              new Padding(
                padding: EdgeInsets.all(5.0),
                child: new Image.asset(
                  "images/icon_safe.png",
                  scale: 1.7,
                ),
              ),
              Text(' '),
              new Expanded(
                  child: new TextField(
                controller: codeController,
                keyboardAppearance: Brightness.light,
                keyboardType: TextInputType.numberWithOptions(),
                maxLines: 1,
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                cursorColor: mainColor,
                decoration: new InputDecoration(
                    hintText: "输入验证码",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
            ],
          ),
          new Container(
            width: ScreenUtil.getInstance().setWidth(DP_200 + 5),
            height: ScreenUtil.getInstance().setHeight(DP_50),
            margin: EdgeInsets.fromLTRB(0, 0, 0, 8),
            decoration: new BoxDecoration(
                color: codeStatus == 0
                    ? Color.fromARGB(255, 99, 99, 99)
                    : mainColor,
                borderRadius: BorderRadius.circular(20.0)),
            child: new FlatButton(
              child: new Padding(
                padding: EdgeInsets.all(0.0),
                child: new Text(
                  codeString,
                  style: new TextStyle(
                      color: Colors.white,
                      fontSize:
                          ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE)),
                ),
              ),
              onPressed: () {
                if (codeStatus == 0) {
                  return;
                }
                if (userController.text.isEmpty) {
                  Fluttertoast.showToast(msg: "请输入手机号");
                  return;
                }
                showDialog(
                    context: context,
                    barrierDismissible: false,
                    builder: (_) {
                      return new NetLoadingDialog(
                        loadingText: "获取中...",
                        bgColor: Color.fromARGB(255, 0, 0, 0),
                        requestCallBack: null,
                        outsideDismiss: false,
                      );
                    });
                getPhoneCode();
              },
            ),
          )
        ],
      ),
    );
  }

  getPhoneCode() async {
    Map map = new Map();
    map['phone'] = userController.text;
    map['sign_type'] = SignType.SEND_PHONE_CODE;
    Response<String> response =
        await HttpUtil().post(Api.SEND_PHONE_CODE, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      setState(() {
        codeStatus = 0;
        if (_countdownTimer != null) {
          return;
        }
        codeString = '${_countdownNum--}重新获取';
        _countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
          setState(() {
            if (_countdownNum > 0) {
              codeStatus = 0;
              codeString = '${_countdownNum--}重新获取';
            } else {
              codeString = '获取验证码';
              codeStatus = 1;
              _countdownNum = 59;
              _countdownTimer.cancel();
              _countdownTimer = null;
            }
          });
        });
      });
    }
  }

// ignore: missing_function_parameters
  Widget loginTopImg() {
    return new Padding(
        padding: EdgeInsets.all(ScreenUtil.getInstance().setWidth(DP_100)),
        child: Material(
          elevation: 12,
          color: Colors.transparent,
          borderRadius:
              BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_30)),
          child: new Image.asset(
            'images/app_icon.png',
            fit: BoxFit.cover,
            width: ScreenUtil.getInstance().setHeight(DP_150),
            height: ScreenUtil.getInstance().setHeight(DP_150),
          ),
        ));
  }

  Widget loginUserEditInput() {
    return new Padding(
      padding: EdgeInsets.fromLTRB(
          ScreenUtil.getInstance().setWidth(DP_100),
          ScreenUtil.getInstance().setHeight(DP_40),
          ScreenUtil.getInstance().setWidth(DP_100),
          0.0),
      child: new Stack(
        alignment: Alignment(1.0, 1.0),
        children: <Widget>[
          new Row(
            children: <Widget>[
              new Padding(
                padding: EdgeInsets.all(5.0),
                child: new Image.asset(
                  "images/icon_phone.png",
                  scale: 1.7,
                ),
              ),
              Text(' '),
              new Expanded(
                  child: new TextField(
                controller: userController,
                keyboardAppearance: Brightness.light,
                keyboardType: TextInputType.numberWithOptions(),
                maxLines: 1,
                cursorColor: mainColor,
                style: TextStyle(
                    color: Colors.black54,
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                decoration: new InputDecoration(
                    hintText: "请输入手机号",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        wordSpacing: 0,
                        color: Colors.black38,
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
            ],
          ),
          // new IconButton(
          //     icon: new Image.asset(
          //       "images/del_input.png",
          //       width: ScreenUtil.getInstance().setWidth(DP_20),
          //       height: ScreenUtil.getInstance().setWidth(DP_20),
          //     ),
          //     onPressed: () {
          //       userController.clear();
          //     })
        ],
      ),
    );
  }

  Widget loginPassEditInput() {
    return new Padding(
      padding: EdgeInsets.fromLTRB(
          ScreenUtil.getInstance().setWidth(DP_100),
          ScreenUtil.getInstance().setHeight(DP_20),
          ScreenUtil.getInstance().setWidth(DP_100),
          0.0),
      child: new Stack(
        alignment: Alignment(1.0, 1.0),
        children: <Widget>[
          new Row(
            children: <Widget>[
              new Padding(
                padding: EdgeInsets.all(5.0),
                child: new Image.asset(
                  "images/icon_lock.png",
                  scale: 1.7,
                ),
              ),
              Text(' '),
              new Expanded(
                  child: new TextField(
                controller: passController,
                cursorColor: mainColor,
                style: TextStyle(
                    color: Colors.black54,
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                obscureText: true,
                keyboardAppearance: Brightness.light,
                decoration: new InputDecoration(
                    hintText: "请输入密码",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        color: Colors.black38,
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
            ],
          ),
          // new IconButton(
          //     icon: new Image.asset(
          //       "images/del_input.png",
          //       width: ScreenUtil.getInstance().setWidth(DP_20),
          //       height: ScreenUtil.getInstance().setWidth(DP_20),
          //     ),
          //     onPressed: () {
          //       passController.clear();
          //     })
        ],
      ),
    );
  }

  Widget loginButton(BuildContext context) {
    return new Container(
      width: ScreenUtil.getInstance().setWidth(550.00),
      height: ScreenUtil.getInstance().setWidth(DP_90),
      margin: EdgeInsets.fromLTRB(
          0, ScreenUtil.getInstance().setWidth(DP_90), 0, 0),
      decoration: new BoxDecoration(
          color: mainColor,
          borderRadius:
              BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_80))),
      padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
      child: new FlatButton(
        child: new Padding(
          padding: EdgeInsets.all(0.0),
          child: new Text(
            "登录",
            style: new TextStyle(
                color: Colors.white,
                fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
          ),
        ),
        onPressed: () {
          _checkSub(context);
        },
      ),
    );
  }

  Widget loginTip(BuildContext context) {
    return new Container(
      width: ScreenUtil.getInstance().setWidth(550.00),
      margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
      child: new Row(
        children: <Widget>[
          // Expanded(
          //   flex: 1,
          //   child: new GestureDetector(
          //     child: Text(
          //       "注册账号",
          //       style: new TextStyle(
          //           color: Colors.grey,
          //           fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
          //     ),
          //     onTap: () {
          //       toRegister(context);
          //     },
          //   ),
          // ),
          Expanded(
            flex: 1,
            child: new GestureDetector(
              behavior: HitTestBehavior.opaque,
              child: Text(
                "忘记密码?",
                textAlign: TextAlign.center,
                style: new TextStyle(
                    color: Colors.grey,
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
              ),
              onTap: toFindPwd,
            ),
          ),
//
        ],
      ),
    );
  }

  Widget initMoreLogin(BuildContext context) {
    return new Container(
      padding: EdgeInsets.fromLTRB(
          ScreenUtil.getInstance().setWidth(DP_100),
          ScreenUtil.getInstance().setWidth(DP_100),
          ScreenUtil.getInstance().setWidth(DP_100),
          10),
      margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
      child: new Row(
        children: <Widget>[
          Expanded(
            child: Container(
              margin: EdgeInsets.fromLTRB(0, 0, 20, 0),
              height: 1,
              color: Colors.grey,
            ),
          ),
          Text(
            "更多登录方式",
            textAlign: TextAlign.right,
            style: new TextStyle(color: Colors.grey, fontSize: 14),
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.fromLTRB(20, 0, 0, 0),
              height: 1,
              color: Colors.grey,
            ),
          ),
        ],
      ),
    );
  }

  void toFindPwd() {
    Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
      return new ResetPwdPage();
    }));
  }

  void toRegister(BuildContext context) {
    Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
      return new RegisterPage();
    }));
  }

  @override
  void dispose() {
    super.dispose();
    if (codeOpen) {
      _countdownTimer.cancel();
      _countdownTimer = null;
    }
  }

  Future<void> _checkSub(BuildContext context) async {
    if (codeOpen) {
      if (userController.text == "") {
        Fluttertoast.showToast(msg: "请输入手机号");
        return;
      }
      if (codeController.text == "") {
        Fluttertoast.showToast(msg: "请输入短信验证码");
        return;
      }
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (_) {
            return new NetLoadingDialog(
              loadingText: "登录中...",
              bgColor: Color.fromARGB(255, 0, 0, 0),
              requestCallBack: null,
              outsideDismiss: false,
            );
          });
      Map map = new Map();
      map['phone'] = userController.text;
      map['code'] = codeController.text;
      map['sign_type'] = SignType.LOGIN_BY_CODE;
      Response<String> response =
          await HttpUtil().post(Api.LOGIN_BY_CODE, data: getSign(map));
      Map userMap = json.decode(response.data);
      int code = userMap["code"];
      String msg = userMap["msg"];
      Navigator.of(context).pop(1);
      Fluttertoast.showToast(msg: msg);
      if (code == 1 && mounted) {
        saveString(TOKEN, userMap['data']['token']);
        saveString(UID, userMap['data']['uid'].toString());
        saveString(GROUP_ID, userMap['data']['group_id'].toString());
        saveString(PHONE, userController.text);
        APPLIC.eventBus.fire(LoginEvent());
        if (APPLIC.GG == 1) {
          Navigator.of(context).pop();
          Navigator.of(context).pop();
          APPLIC.GG = 0;
        } else {
          Navigator.of(context).pop();
          Navigator.of(context).pop();
          APPLIC.GG = 0;
        }
      }
      return;
    }
    String msgStr = "";
    if (!userController.text.isNotEmpty) {
      msgStr = "用户账号不能为空";
    } else if (!passController.text.isNotEmpty) {
      msgStr = "用户密码不能为空";
    }

    if (msgStr != '') {
      showDialog(
          context: context,
          builder: (context) {
            return new AlertDialog(
              title: new Text("提示信息"),
              content: new Text(msgStr),
              actions: <Widget>[
                new FlatButton(
                    child: new Text("确定"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    }),
              ],
            );
          });
    } else {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (_) {
            return new NetLoadingDialog(
              loadingText: "登录中...",
              bgColor: Color.fromARGB(255, 0, 0, 0),
              requestCallBack: null,
              outsideDismiss: false,
            );
          });
      login();
    }
  }

  login() async {
    Map map = new Map();
    map['account'] = userController.text;
    map['pwd'] = passController.text;
    map['sign_type'] = SignType.USER_LOGIN;
    Response<String> response =
        await HttpUtil().post(Api.USER_LOGIN, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      saveString(TOKEN, userMap['data']['token']);
      saveString(UID, userMap['data']['uid'].toString());
      saveString(GROUP_ID, userMap['data']['group_id'].toString());
      saveString(PHONE, userController.text);
      APPLIC.eventBus.fire(LoginEvent());
      saveString(PWD, passController.text);
      if (APPLIC.GG == 1) {
        Navigator.of(context).pop();
        Navigator.of(context).pop();
        APPLIC.GG = 0;
      } else {
        Navigator.of(context).pop();
        Navigator.of(context).pop();
        APPLIC.GG = 0;
      }
    }
    return true;
  }
}
